﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Diagnostics;
using System.Configuration;
using TvViewer.settings;
using Microsoft.Win32;
using System.IO;


namespace TvViewer
{
  [RunInstaller(true)]
  public partial class InstallerCore : Installer
  {
    public InstallerCore()
    {
      InitializeComponent();
    }

    public override void Install(IDictionary stateSaver)
    {
      base.Install(stateSaver);
      //Debugger.Break();

      //todo: find a way to get the path of the user.config file and delete old files
      //C:\Users\DieBagger\AppData\Local\Team_MediaPortal\TvViewer.exe_Url_i5twurvuwglp2xg1rm2xovdaf52y4um2
      //ExeConfigurationFileMap execonfig = new ExeConfigurationFileMap();
      //string path = System.Windows.Forms.Application.LocalUserAppDataPath;
      //Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
      //Console.WriteLine("Local user config path: {0}", config.FilePath);
      //try
      //{
      //  File.Delete(config.FilePath);
      //}
      //catch (Exception ex)
      //{ }


      string targetDirectory = Context.Parameters["targetdir"];
      string installType = Context.Parameters["installtype"];
      string exePath = string.Format("{0}TvViewer.exe.config", targetDirectory);

      
      string server = Context.Parameters["server"];
      string port = Context.Parameters["port"];
      int intPort;
      if (!Int32.TryParse(port, out intPort))
      {//port invalid, use default
        port = "8080";
      }

      string webservicesUrl = Util.CreateWebServiceUrl(server, port);
      Util.ChangeSettingsValue(exePath, "TvViewer_MpTvService_ServiceInterface", webservicesUrl);

      if (installType.Equals("core"))
      {//only core install
        Util.ChangeSettingsValue(exePath, "UseInternalVlc", "False");
      }
      else
      {//full install
        Util.ChangeSettingsValue(exePath, "UseInternalVlc", "True");
      }
      Util.ChangeSettingsValue(exePath, "FirstTime", "True");

      try
      {
        //try to get the vlc path from registry
        RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\VideoLAN\\VLC");
        if (masterKey != null)
        {
          String installPath = masterKey.GetValue("InstallDir") as String;
          Util.ChangeSettingsValue(exePath, "ExternalVlcPath", installPath);

        }
        masterKey.Close();
      }
      catch (Exception)
      { }
    }
  }
}
